import { director, Game, game} from "cc";
import { BundleType } from "../../Enum/FramworkEnums";
import Singleton from "../../framework/bo/Singleton";
import { UIManager } from "../../framework/manager/uiManager";
import { AccountService } from "../logic/service/AccountService";
import ClientContext from "./ClientContext";
import BundleManager from "../../framework/manager/BundleManager";
import NetData from "../../framework/net/NetData";
import LogicBoot from "../logic/LogicBoot";
import { PoolManager } from "../../framework/manager/poolManager";
import { ClientEvent } from "../../framework/bo/ClientEvent";

export default class ClientManager extends Singleton {

    private clientContext: ClientContext = ClientContext.Instance;

    public static get Instance(): ClientManager {
        return super.GetInstance<ClientManager>();
    }
    /**
     * 加载大厅场景
     */
    async loadingHall() {
        const userInfo2 = this.clientContext.userInfo;
        let loginRes = await AccountService.Instance.login(userInfo2.account, userInfo2.password, this.clientContext.areaVo.areaId, userInfo2.platformId);
        if (loginRes) {
            await BundleManager.Instance.initBundle(BundleType.hall);// 加载大厅分包
            await BundleManager.Instance.loadScenceSync("hall", BundleType.hall);
        } else {
            console.log("登录失败");
        }
    }

    loadingGame() {// 加载游戏登陆场景
        director.loadScene("select");
    }

    /**重启游戏调用 
    * 游戏重启 必要的需要重制资源和引用 否则程序会崩溃
    * 游戏重启除热更外 非必要不可调用，建议采用加载到登陆场景的形式替代
    * @param [flag=false] 默认false表示重启游戏，当为true时指定游戏加载到登陆场景重新连接服务器而不是重启
   */
    gameRestart(flag: boolean = false) {
        let context = ClientContext.Instance;
        if (context.hallSocketManager != null) //断线
            context.hallSocketManager.closeSocket();
        if (flag) {
            ClientManager.Instance.loadingGame();
            return;
        }

        LogicBoot.Instance.clear();
        ClientEvent.clear();
        NetData.pbRoot = null;
        UIManager.instance.clear()// 必要 涉及ui资源引用
        PoolManager.instance.clear()// 必要 涉及资源引用
        BundleManager.Instance.clear()
        context.clear()
        setTimeout(async () => {
            // game.off(Game.EVENT_SHOW) //暂未使用 游戏重启时这些事件会被cocos暂存，如果使用了建议清理以避免重复添加事件
            // game.off(Game.EVENT_HIDE)
            game.restart();
        }, 1000)//重启游戏
    }
}